package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.context.WeChatPayStrategyContext;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.strategy.WeChatPayStrategy;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.QueryOrderByOutTradeNoRequest;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Autowired
	private PaymentInfoService paymentInfoService;

	@Autowired
	private RSAAutoCertificateConfig rsaAutoCertificateConfig ;

	@Autowired
	private WxPayV3Config wxPayV3Config ;

	@Override
	public WeChatPayVo createJsapi(String paymentType, String orderNo) {   // 支付类型：1301-订单 1302-充值
		WeChatPayStrategy weChatPayStrategy = WeChatPayStrategyContext.getWeChatPayStrategy(paymentType);
		WeChatPayVo weChatPayVo = weChatPayStrategy.createJsapi(paymentType, orderNo);
		return weChatPayVo;
	}

	@Override
	public Boolean queryPayStatus(String orderNo) {

		// 创建QueryOrderByOutTradeNoRequest对象
		QueryOrderByOutTradeNoRequest queryOrderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest() ;
		queryOrderByOutTradeNoRequest.setOutTradeNo(orderNo);
		queryOrderByOutTradeNoRequest.setMchid(wxPayV3Config.getMerchantId());

		// 请求微信支付平台的查询订单状态接口
		JsapiServiceExtension jsapiServiceExtension = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();
		Transaction transaction = jsapiServiceExtension.queryOrderByOutTradeNo(queryOrderByOutTradeNoRequest);

		// 从Transaction对象中获取支付结果
		if(transaction != null) {
			Transaction.TradeStateEnum tradeStateEnum = transaction.getTradeState();
			if(Transaction.TradeStateEnum.SUCCESS == tradeStateEnum) {
				// 支付成功了， 更改交易信息的状态，更新订单的状态，保存的购买信息
				paymentInfoService.updatePaymentInfo(transaction) ;
				return true ;

			}
		}

		// 返回
		return false;
	}

	@Override
	public void asyncNotify(HttpServletRequest request) {
		
		// 获取指定请求头的数据
		String wechatPaySerial = request.getHeader("Wechatpay-Serial");
		String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
		String wechatSignature = request.getHeader("Wechatpay-Signature");
		String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");

		// 读取请求体中的数据
		String requestBody = PayUtil.readData(request);

		// 获取通知结果数据，执行后期的业务流程操作
		// 构造 RequestParam
		RequestParam requestParam = new RequestParam.Builder()
				.serialNumber(wechatPaySerial)
				.nonce(wechatpayNonce)
				.signature(wechatSignature)
				.timestamp(wechatTimestamp)
				.body(requestBody)
				.build();

		// 初始化 NotificationParser
		NotificationParser parser = new NotificationParser(rsaAutoCertificateConfig);
		Transaction transaction = parser.parse(requestParam, Transaction.class);

		// 从Transaction对象中获取支付结果
		if(transaction != null) {
			Transaction.TradeStateEnum tradeStateEnum = transaction.getTradeState();
			if(Transaction.TradeStateEnum.SUCCESS == tradeStateEnum) {
				log.info("异步通知获取到了支付状态....");
				paymentInfoService.updatePaymentInfo(transaction) ;			// 支付成功了， 更改交易信息的状态，更新订单的状态，保存的购买信息
			}
		}

	}

}
